﻿using Abp.Application.Services.Dto;
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.EntityFrameworkCore.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.UI;
using Camc.Quality.Authorization.Users;
using Camc.Quality.Bom;
using Camc.Quality.Bop;
using Camc.Quality.Common;
using Camc.Quality.DataDictionary;
using Camc.Quality.IOperationHistory;
using Camc.Quality.Materials;
using Camc.Quality.OperationHistory;
using Camc.Quality.TrepanningManager.CollectBomDto;
using EFCore.BulkExtensions;
using Microsoft.EntityFrameworkCore;
using Org.BouncyCastle.Utilities.Collections;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
namespace Camc.Quality.TrepanningManager.CollectBom
{

    public class CollectBomAppService : QualityAppServiceBase
    {
        private readonly IRepository<MaterialsContent, Guid> _materialsContentRepository;
        private readonly IRepository<BomDesign, Guid> _bomDesignrepository;
        private readonly IRepository<BomDesignDetail, Guid> _bomDesignDetailrepository;
        private readonly IRepository<CollectBomManager, Guid> _collectBomManagerrepository;
        private readonly IRepository<User, long> _userRepository;
        private readonly IRepository<MaterialsNode, Guid> _materialsNodeRepository;
        private readonly IRepository<Sys_Code, Guid> _sysCodeRepository;
        private readonly IRepository<CollectBomManagerChild, Guid> _collectBomManagerChildRepository;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly IOperationHistoryAppService _iOperationHistoryAppService;
        int calculate = 1;
        public CollectBomAppService(IRepository<MaterialsContent, Guid> materialsContentRepository, IRepository<BomDesign, Guid> bomDesignrepository, IRepository<BomDesignDetail, Guid> bomDesignDetailrepository, IRepository<User, long> userRepository, IRepository<CollectBomManager, Guid> collectBomManagerrepository, IRepository<MaterialsNode, Guid> materialsNodeRepository, IRepository<Sys_Code, Guid> sysCodeRepository, IUnitOfWorkManager unitOfWorkManager, IRepository<CollectBomManagerChild, Guid> collectBomManagerChildRepository, IOperationHistoryAppService iOperationHistoryAppService)
        {
            _materialsContentRepository = materialsContentRepository;
            _bomDesignrepository = bomDesignrepository;
            _bomDesignDetailrepository = bomDesignDetailrepository;
            _userRepository = userRepository;
            _collectBomManagerrepository = collectBomManagerrepository;
            _materialsNodeRepository = materialsNodeRepository;
            _sysCodeRepository = sysCodeRepository;
            _unitOfWorkManager = unitOfWorkManager;
            _collectBomManagerChildRepository = collectBomManagerChildRepository;
            _iOperationHistoryAppService = iOperationHistoryAppService;
        }
        ///// <summary>
        ///// 获取型号
        ///// </summary>
        ///// <returns></returns>
        //public async Task<List<CollectBomManagerOtherDto>> GetModule()
        //{
        //    var queryModuleDatas = from queryModuleData in _materialsContentRepository.GetAll().Where(t => t.MaterialCategoryId == Guid.Empty && t.MaterialProperty == 0)
        //                           join queryBomDesignData in _bomDesignrepository.GetAll() on queryModuleData.Id equals queryBomDesignData.MaterialsContentId
        //                           select new CollectBomManagerOtherDto
        //                           {
        //                               label = queryModuleData.Model,
        //                               value = queryModuleData.Id
        //                           };
        //    if (queryModuleDatas.Count() > 0)
        //    {
        //        return queryModuleDatas.ToList();
        //    }
        //    return new List<CollectBomManagerOtherDto>();
        //}

        /// <summary>
        /// 获取发次
        /// </summary>
        /// <returns></returns>
        public async Task<List<CollectBomManagerOtherDto>> GetSendTime(Guid module)
        {
            var querySendTimeDatas = from querySendTimeData in _bomDesignrepository.GetAll().Where(t => t.ModuleId == module)
                                     select new CollectBomManagerOtherDto
                                     {
                                         label = querySendTimeData.SendTime,
                                         value = querySendTimeData.SendTimeId
                                     };
            if (querySendTimeDatas.Count() > 0)
            {
                return querySendTimeDatas.ToList();
            }
            return new List<CollectBomManagerOtherDto>();
        }
 
        /// <summary>
        /// 生成汇总BOM
        /// </summary>
        /// <param name="collectBomManagerDto"></param>
        /// <returns></returns>
        public ResultMessage AddBomCollect(CollectBomManagerDto collectBomManagerDto)
        {
            ResultMessage resultMessage = new ResultMessage();
            if (collectBomManagerDto.XJId == Guid.Empty || string.IsNullOrEmpty(collectBomManagerDto.Module) || string.IsNullOrEmpty(collectBomManagerDto.SendTime))
            {
                resultMessage.code = 1;
                resultMessage.Message = "请选择型号发次芯级";
                return resultMessage;
            }
            try
            {
                
                var queryBomDesign = _bomDesignrepository.FirstOrDefaultAsync(t => t.SendTimeId.ToString() == collectBomManagerDto.SendTime && t.ModuleId.ToString() == collectBomManagerDto.Module).Result;

                List<BomDesignDetail> bomDesignDetails = new List<BomDesignDetail>();
                if (queryBomDesign != null)
                {
                    //获取bom详细信息  获取审批通过的数据？？？后期加
                    var queryBomDesignDetials = from queryBomDesignDetial in _bomDesignDetailrepository.GetAll().Where(t => t.BomDesignId == queryBomDesign.Id && t.ParentId == Guid.Empty && t.Id == collectBomManagerDto.XJId)
                                                join materilsContent in _materialsContentRepository.GetAll() on queryBomDesignDetial.MaterialId equals materilsContent.Id
                                                join code in _sysCodeRepository.GetAll() on queryBomDesign.ModuleId equals code.Id
                          into codeData
                                                from cd in codeData.DefaultIfEmpty()
                                                join code2 in _sysCodeRepository.GetAll() on queryBomDesign.SendTimeId equals code2.Id
                                                            into code2
                                                from cd2 in code2.DefaultIfEmpty()
                                                select new CollectBomManager
                                                {
                                                    Module = cd.Description,
                                                    ModuleId = queryBomDesign.ModuleId,
                                                    SendTime = cd2.Description,
                                                    SendTimeId = queryBomDesign.SendTimeId,
                                                    XJName = materilsContent.MaterialName,
                                                    XJDrawingNo = materilsContent.MaterialNo,
                                                    BomDesignId = queryBomDesign.Id,
                                                    XJId = queryBomDesignDetial.Id,
                                                    CreatorUserId = queryBomDesignDetial.CreatorUserId
                                                };
                    if (queryBomDesignDetials.Count() == 0)
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = "设计bom没有对应的数据";
                        return resultMessage;
                        //throw new UserFriendlyException("设计bom没有对应的数据");
                    }
                    var queryCollectBomManager = _collectBomManagerrepository.FirstOrDefaultAsync(t => t.XJId == collectBomManagerDto.XJId).Result;
                    Guid guid = Guid.Empty;
                    if (queryCollectBomManager == null)
                    {
                        guid = _collectBomManagerrepository.InsertAndGetId(queryBomDesignDetials.ToList()[0]);
                        _unitOfWorkManager.Current.SaveChanges();
                        _iOperationHistoryAppService.InsertOperationLogNew(guid, BusinessTypes.BOM汇总, OperationTypes.新增, "BOM汇总新增："+ queryBomDesignDetials.ToList()[0].XJName);
                    }
                    else
                    {
                        _collectBomManagerrepository.Update(queryCollectBomManager);
                        _iOperationHistoryAppService.InsertOperationLogNew(queryCollectBomManager.Id, BusinessTypes.BOM汇总, OperationTypes.修改, "BOM汇总更新：" + queryCollectBomManager.XJName);
                    }
                    #region 汇总零件数量
                    //找出芯级下的所有部套   后期 添加审核通过的 （后期加）
                    var departmentDatas = _bomDesignDetailrepository.GetAll().Where(t => t.ParentId == collectBomManagerDto.XJId && t.Status == DocumentStatus.已发布);
                    if (departmentDatas.Count() == 0)
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = "该芯级下没有对应的部套数据或数据未核审";
                        return resultMessage;
                        //throw new UserFriendlyException("该芯级下没有对应的部套数据");
                    }
                    List<BomDesignDetail> bomDesignDetailsList = new List<BomDesignDetail>();
                    // **根据芯级找出所有部套下的所有组件和零件
                    foreach (BomDesignDetail designDetail in departmentDatas)
                    {
                        //找出每个部套下的零件
                        var materilsList = from queryMaterilsList in _bomDesignDetailrepository.GetAll().Where(t => t.LevelRelationship.StartsWith(designDetail.LevelRelationship) && t.BomDesignId == queryBomDesign.Id && (t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件 || t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件)) select queryMaterilsList;
                        bomDesignDetailsList.AddRange(materilsList);
                    }
                    //找出所有已发布部套下的零件(因先汇总再对比 所以不需要取组件 因为汇总已经汇总到零件上了)
                    //var materilsList  = from queryMaterilsList in bomdesignDetailLists.Where(t=>t.LevelRelationship)

                    if (bomDesignDetailsList.Count() == 0)
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = "该部套下没有对应的零件";
                        return resultMessage;
                        //throw new UserFriendlyException("该部套下没有对应的零件");
                    }
                    var querycollectChildAll = _collectBomManagerChildRepository.GetAll().ToList();
                    var querycollectManager = _collectBomManagerrepository.GetAll().ToList();
                    var list = ObjectMapper.Map<List<CollectBomManagerChild>>(bomDesignDetailsList);

                    var queryCollectList = querycollectChildAll.Where(t => t.CollectBomManagerId == (queryCollectBomManager == null ? guid : queryCollectBomManager.Id));
                    List<CollectBomManagerChild> collectBomManagerChildren = new List<CollectBomManagerChild>();
             
                    
                    if (queryCollectList != null && queryCollectList.Count() > 0)
                    {
                        for (int c = list.Count - 1; c >= 0; c--) 
                        {
                            int bomUnit = list[c].Unit1BomDosage;
                            var collectBomContent = querycollectChildAll.FirstOrDefault(k => k.Id == list[c].Id);
                            if (collectBomContent != null)
                            {
                                //
                                collectBomContent.CollectBomManagerId = queryCollectBomManager.Id;
                                collectBomContent.Unit1BomDosage = bomUnit;
                                collectBomManagerChildren.Add(collectBomContent);
                                list.Remove(list[c]);
                            }
                            else
                            {
                                list[c].CollectBomManagerId = queryCollectBomManager.Id;
                                collectBomManagerChildren.Add(list[c]);
                                list.Remove(list[c]);
                            }
                        }
                        _collectBomManagerChildRepository.GetDbContext().BulkInsertOrUpdate(collectBomManagerChildren);
                        _collectBomManagerChildRepository.GetDbContext().SaveChanges();

                    }
                    else
                    {
                        collectBomManagerChildren.Clear();
                        foreach (CollectBomManagerChild collectBomManagerChild in list)
                        {
                            //Guid stringGuid = Guid.Empty;
                            //stringGuid = collectBomManagerChild.Id;
                            collectBomManagerChild.CollectBomManagerId = queryCollectBomManager == null ? guid : queryCollectBomManager.Id;
                            //    collectBomManagerChild.CreationTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffffff");
                            //  collectBomManagerChild.Id = stringGuid;
                            collectBomManagerChildren.Add(collectBomManagerChild);
                        }
                        _collectBomManagerChildRepository.GetDbContext().BulkInsert(collectBomManagerChildren);
                        _collectBomManagerChildRepository.GetDbContext().SaveChanges();
                    }
                    queryCollectList = _collectBomManagerChildRepository.GetAll().Where(t => t.CollectBomManagerId == (queryCollectBomManager == null ? guid : queryCollectBomManager.Id));
                    //from bomDesignDetailBT in departmentDatas
                    //                 join bomDesignDetailZJ in _bomDesignDetailrepository.GetAll().Where(t=>t.LevelRelationship.StartsWith()) on bomDesignDetailBT.Id equals
                    //                 bomDesignDetailZJ.ParentId
                    //                 select bomDesignDetailZJ;
                    //找出组件下的组件 然后合并一个结果集&&t.MaterialProperty ==(int)MaterialsEnum.MaterialProperty.组件
                    //departmentDatas.ToList().ForEach(t => {
                    //    var bomDesignDataChildZJList = _bomDesignDetailrepository.GetAll().Where(k => k.LevelRelationship.StartsWith(t.LevelRelationship)&&k.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件);
                    //    bomDesignDetails.AddRange(bomDesignDataChildZJList);
                    //});
                    // **根据组件找出所有零件
                    if (queryCollectList.Count() > 0&& queryCollectList!=null)
                    {
                        //var partsDatas = from bomDesignDetailBT in componentDatas.ToList().Union(bomDesignDetails)
                        //                 join bomDesignDetailLJ in _bomDesignDetailrepository.GetAll().Where(t => t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件) on bomDesignDetailBT.Id equals
                        //                     bomDesignDetailLJ.ParentId
                        //                 select bomDesignDetailLJ;
                        ////将组件和对应 组件下的零件进行合并，并根据 层级排序
                        //var unionAllData = (bomDesignDetails).Union(partsDatas).ToList().OrderBy(t => t.LevelNum
                        //);
                        //过滤出零件 以零件往上找
                        collectBomManagerChildren.Clear();
                        var parters = queryCollectList.Where(t => t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件).ToList();
                        //unionAllData.Where(t=>t.p)
                        //循环部套 id 找出对应的 组件
                        foreach (CollectBomManagerChild partsDetaillist in parters)
                        {
                            OrderBomDetaillist(queryCollectList.ToList(), partsDetaillist.Id
                                );
                            partsDetaillist.BomDosageTotalAmount = calculate;
                            //   collectBomManagerChildren.Update(partsDetaillist);
                            collectBomManagerChildren.Add(partsDetaillist);
                            calculate = 1;
                        }
                        _collectBomManagerChildRepository.GetDbContext().BulkUpdate(collectBomManagerChildren);
                        _collectBomManagerChildRepository.GetDbContext().SaveChanges();
                    }
                    #endregion
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        ///// <summary>
        ///// 获取芯级
        ///// </summary>
        ///// <returns></returns>
        //public async Task<List<CollectBomManagerOtherDto>> GetXj(CollectBomManagerEditDto collectBomManagerEditDto)
        //{
        //    //根据型号、发次 获取芯级
        //    var queryXjDatas = from queryXjData in _bomDesignrepository.GetAll().Where(t => t.SendTimeId == collectBomManagerEditDto.SendTimeId && t.ModuleId == collectBomManagerEditDto.ModuleId)
        //                       join queryBomDesignDetailData in _bomDesignDetailrepository.GetAll().Where(t => t.ParentId == Guid.Empty && t.LevelNum == 2) on queryXjData.Id equals queryBomDesignDetailData.BomDesignId
        //                       join queryMaterialsData in _materialsContentRepository.GetAll() on queryBomDesignDetailData.MaterialId equals queryMaterialsData.Id
        //                       select new CollectBomManagerOtherDto
        //                       {
        //                           label = queryMaterialsData.MaterialName,
        //                           value = queryBomDesignDetailData.Id
        //                       };
        //    if (queryXjDatas.Count() > 0)
        //    {
        //        return queryXjDatas.ToList();
        //    }
        //    return new List<CollectBomManagerOtherDto>();
        //}
        /// <summary>
        /// 对结果集进行重组
        /// </summary>
        /// <param name="queryBomData"></param>
        /// <returns></returns>
        List<CollectBomManagerChild> bomDetaillists = new List<CollectBomManagerChild>();
        private void OrderBomDetaillist(List<CollectBomManagerChild> unionAllData, Guid guid)
        {

            List<CollectBomManagerChild> queryBom = unionAllData.Where(t => t.Id == guid).ToList();
             if (unionAllData.Count > 0 && queryBom != null && queryBom.Count > 0)
            {
                if (queryBom.Count > 0)
                {
                    foreach (CollectBomManagerChild  collectBomManagerChild in queryBom)
                    {
                        // bomDetaillists.Add(bomDetaillist);
                        //零件上一级
                        //calculate *= bomDetaillist.Unit1BomDosage;
                        if (collectBomManagerChild.Unit1BomDosage==0) 
                        {
                            collectBomManagerChild.Unit1BomDosage = 1;
                        }
                        calculate *= collectBomManagerChild.Unit1BomDosage;
                        OrderBomDetaillist(unionAllData, collectBomManagerChild.ParentId);
                    }
                }
            }
        }
        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<CollectBomManagerDto>> GetCollectBomContent(CollectBomManagerEditDto input)
        {
                var userData = _userRepository.GetAll().ToList();
            var queryCollectBomContents = from queryCollectBomContent in _collectBomManagerrepository.GetAll().WhereIf(input.ModuleId != Guid.Empty, t => t.ModuleId == input.ModuleId).WhereIf(input.SendTimeId != Guid.Empty, t => t.SendTimeId.Equals(input.SendTimeId)).WhereIf(!input.XJName.IsNullOrWhiteSpace(), t => t.XJId.ToString() == input.XJName)
                                          join users in userData on queryCollectBomContent.CreatorUserId equals users.Id
                                          select new CollectBomManagerDto
                                          {
                                              Module = queryCollectBomContent.Module,
                                              SendTime = queryCollectBomContent.SendTime,
                                              XJName = queryCollectBomContent.XJName,
                                              XJId = queryCollectBomContent.XJId,
                                              XJDrawingNo = queryCollectBomContent.XJDrawingNo,
                                              BomDesignId = queryCollectBomContent.BomDesignId,
                                              CreateUserName = users.Surname + users.Name,
                                              LastModificationTime = queryCollectBomContent.LastModificationTime,
                                              CreationTime = queryCollectBomContent.CreationTime,
                                              Id = queryCollectBomContent.Id
                                              };
                if (queryCollectBomContents != null)
                {
                    try
                    {
                        var collectBomContents = await queryCollectBomContents.OrderBy(input.Sorting).PageBy(input).ToListAsync();
                        return new PagedResultDto<CollectBomManagerDto>(queryCollectBomContents.Count(), collectBomContents);
                    }
                    catch (Exception ex)
                    {
                        throw new UserFriendlyException("系统内部错误,请重试或联系管理员");
                    }
                }
                else
                {
                    throw new UserFriendlyException("异常,请重试或联系管理员");
                }
        }
        /// <summary>
        /// 单条查看bom芯级物料汇总
        /// </summary>
        /// <param name="xjId"></param>
        /// <returns></returns>
        public  List<CollectBomMaterialsContentDto> GetCollectBomMaterialsContent(Guid xjId)
        {
            if (xjId != Guid.Empty)
            {
                var queryCollecBomData = _collectBomManagerChildRepository.GetAll().ToList();
                var queryMaterialsList = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == xjId).Result;
                if (queryMaterialsList != null)
                {
                    var queryContent = from queryAll in (from queryBomMaterils in queryCollecBomData.Where(t => t.BomDesignId == queryMaterialsList.BomDesignId && t.LevelRelationship.StartsWith(queryMaterialsList.LevelRelationship) && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件)
                                                         join queryMaterilsContent in _materialsContentRepository.GetAll() on queryBomMaterils.MaterialId equals queryMaterilsContent.Id
                                                         join queryNode in _materialsNodeRepository.GetAll() on queryMaterilsContent.MaterialsNodeId equals queryNode.Id
                                                         join queryNodeChild in _materialsNodeRepository.GetAll() on queryMaterilsContent.MaterialCategoryId equals queryNodeChild.Id
                                                         join code in _sysCodeRepository.GetAll() on queryMaterilsContent.UnitId equals code.Id
                                                            into codeData
                                                         from cd in codeData.DefaultIfEmpty()
                                                         select new
                                                         {
                                                             Unit1BomDosageXj = queryBomMaterils.BomDosageTotalAmount,
                                                             Id = queryBomMaterils.MaterialId,
                                                             CollectId = queryBomMaterils.Id,
                                                             YearsNo = queryBomMaterils.YearsNo
                                                         })
                                       group queryAll by new { queryAll.Id} into materialsAll
                                       select new
                                       {
                                           Id = materialsAll.Key.Id,
                                           Unit1BomDosageAll = materialsAll.Sum(t => t.Unit1BomDosageXj),
                                           YearsNo = string.Join(",", materialsAll.Select(x=>x.YearsNo).Distinct())
                                           //CollectId = materialsAll.Key.CollectId
                                       };

                    var querymater = from queryBomMaterils in queryCollecBomData.Where(t => t.BomDesignId == queryMaterialsList.BomDesignId && t.LevelRelationship.StartsWith(queryMaterialsList.LevelRelationship) && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件)
                                     join queryMaterilsContent in _materialsContentRepository.GetAll() on queryBomMaterils.MaterialId equals queryMaterilsContent.Id
                                     join queryNode in _materialsNodeRepository.GetAll() on queryMaterilsContent.MaterialsNodeId equals queryNode.Id
                                     join queryNodeChild in _materialsNodeRepository.GetAll() on queryMaterilsContent.MaterialCategoryId equals queryNodeChild.Id
                                     join code in _sysCodeRepository.GetAll() on queryMaterilsContent.UnitId equals code.Id
                                        into codeData
                                     from cd in codeData.DefaultIfEmpty()
                                     select new
                                     {
                                         MaterialName = queryMaterilsContent.MaterialName,
                                         MaterialNo = queryMaterilsContent.MaterialNo,
                                         Model = queryMaterilsContent.Model,
                                         MaterialTypeName = queryNode.MaterialTypeName,
                                         MaterialCategoryName = queryNodeChild.MaterialTypeName,
                                         Unit = cd.Description,
                                         Unit1BomDosageXj = queryBomMaterils.BomDosageTotalAmount,
                                         Id = queryBomMaterils.MaterialId,
                                     };
                    var contentRequest = querymater.GroupBy(c => c.Id).Select(c => c.First());
                    //var contentRequest = querymater.ToList().Where((x, Id) => querymater.ToList().FindIndex(z => z.Id == x.Id) == Id).ToList();
                    var queryAllMaterials = from content in queryContent
                                            join allmater in contentRequest
                                            on content.Id equals allmater.Id
                                            select new CollectBomMaterialsContentDto
                                            {
                                                MerialsId = content.Id,
                                                MaterialName = allmater.MaterialName,
                                                MaterialNo = allmater.MaterialNo,
                                                Model = allmater.Model,
                                                MaterialTypeName = allmater.MaterialTypeName,
                                                MaterialCategoryName = allmater.MaterialCategoryName,
                                                Unit = allmater.Unit,
                                                Unit1BomDosageXj = content.Unit1BomDosageAll,
                                                YearsNo = content.YearsNo==","?"": content.YearsNo
                                                //d = content.CollectId
                                            };


                    if (queryAllMaterials.Count() > 0)
                    {
                        return queryAllMaterials.OrderBy(d=>d.MaterialNo).OrderBy(s => s.Model).ToList();
                    }
                };
            }
            return null;
        }
        /// <summary>
        /// 查看芯级汇总信息
        /// </summary>
        /// <param name="xjId"></param>
        /// <returns></returns>
        public async Task<IQueryable<CollectBomMaterialsContentDto>> GetCollectBomMaterialsContentNB(Guid xjId)
        {
            if (xjId != Guid.Empty) 
            {
                var queryMaterialsList = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == xjId).Result;
                if (queryMaterialsList != null) 
                {
                    var queryCollectBom = _collectBomManagerChildRepository.GetAll().ToList();
                    var queryContent = from queryAll in (from queryBomMaterils in _collectBomManagerChildRepository.GetAll().Where(t => t.BomDesignId == queryMaterialsList.BomDesignId && t.LevelRelationship.StartsWith(queryMaterialsList.LevelRelationship) && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件)
                                                         join queryMaterilsContent in _materialsContentRepository.GetAll() on queryBomMaterils.MaterialId equals queryMaterilsContent.Id
                                                         join queryNode in _materialsNodeRepository.GetAll() on queryMaterilsContent.MaterialsNodeId equals queryNode.Id
                                                         join queryNodeChild in _materialsNodeRepository.GetAll() on queryMaterilsContent.MaterialCategoryId equals queryNodeChild.Id
                                                         join code in _sysCodeRepository.GetAll() on queryMaterilsContent.UnitId equals code.Id
                                                            into codeData
                                                         from cd in codeData.DefaultIfEmpty()
                                                         select new
                                                         {
                                                             Unit1BomDosageXj = queryBomMaterils.BomDosageTotalAmount,
                                                             Id = queryBomMaterils.MaterialId,
                                                             CollectId = queryBomMaterils.Id,
                                                             YearsNo = queryBomMaterils.YearsNo
                                                         })
                                       group queryAll by new { queryAll.Id} into materialsAll
                                       select new
                                       {
                                           Id = materialsAll.Key.Id,
                                           Unit1BomDosageAll = materialsAll.Sum(t => t.Unit1BomDosageXj),
                                           YearsNo = string.Join(",", materialsAll.Select(x => x.YearsNo).Distinct())
                                           //CollectId = materialsAll.Key.CollectId
                                       };
                    var querymater = from queryBomMaterils in _collectBomManagerChildRepository.GetAll().Where(t => t.BomDesignId == queryMaterialsList.BomDesignId && t.LevelRelationship.StartsWith(queryMaterialsList.LevelRelationship) && t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件)
                                     join queryMaterilsContent in _materialsContentRepository.GetAll() on queryBomMaterils.MaterialId equals queryMaterilsContent.Id
                                     join queryNode in _materialsNodeRepository.GetAll() on queryMaterilsContent.MaterialsNodeId equals queryNode.Id
                                     join queryNodeChild in _materialsNodeRepository.GetAll() on queryMaterilsContent.MaterialCategoryId equals queryNodeChild.Id
                                     join code in _sysCodeRepository.GetAll() on queryMaterilsContent.UnitId equals code.Id
                                        into codeData
                                     from cd in codeData.DefaultIfEmpty()
                                     select new 
                                     {
                                         MaterialName = queryMaterilsContent.MaterialName,
                                         MaterialNo = queryMaterilsContent.MaterialNo,
                                         Model = queryMaterilsContent.Model,
                                         MaterialTypeName = queryNode.MaterialTypeName,
                                         MaterialCategoryName = queryNodeChild.MaterialTypeName,
                                         Unit = cd.Description,
                                         Unit1BomDosageXj = queryBomMaterils.BomDosageTotalAmount,
                                         Id = queryBomMaterils.MaterialId,
                                         YearsNo = queryBomMaterils.YearsNo
                                     };
                    var contentRequest = querymater.GroupBy(c => c.Id).Select(c => c.First());
                    var queryAllMaterials = from content in queryContent
                                            join allmater in contentRequest
                                            on content.Id equals allmater.Id
                                            select new CollectBomMaterialsContentDto
                                            {
                                                MerialsId = content.Id,
                                                MaterialName = allmater.MaterialName,
                                                MaterialNo = allmater.MaterialNo,
                                                Model = allmater.Model,
                                                MaterialTypeName = allmater.MaterialTypeName,
                                                MaterialCategoryName = allmater.MaterialTypeName,
                                                Unit = allmater.Unit,
                                                Unit1BomDosageXj = content.Unit1BomDosageAll,
                                                //Id = content.CollectId
                                                YearsNo= content.YearsNo
                                            };
                    if (queryAllMaterials.Count() > 0) 
                    {
                        return queryAllMaterials.OrderByDescending(s=>s.CreationTime);
                    }
                };
            }
            return null;
        }

    }
}
